import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/category.dart';

class CategoryScreen extends StatefulWidget {
  @override
  _CategoryScreenState createState() => _CategoryScreenState();
}

class _CategoryScreenState extends State<CategoryScreen> {
  List<Category> categories = <Category>[];
  RefreshController _refreshController = RefreshController();
  int _loaded = 0;

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _refreshController.requestRefresh();
    });
  }

  Future _getCategories() async {
    List _list = await Category().fetch();
    setState(() {
      categories.clear();
      _list.forEach((_item) => categories.add(Category()..fromJson(_item)));
      _loaded = 1;
    });
    _refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    TextEditingController _nameCtrl = new TextEditingController();

    return Scaffold(
      appBar: AppBar(
        title: Text('分类管理'),
        actions: <Widget>[
          TextButton(
              style: Theme.of(context).useMaterial3 ? null : TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onPrimary),
              onPressed: () async {
                String _name = await showDialog(
                  context: context,
                  builder: (context) {
                    return AlertDialog(
                        title: Text('清输入新的分类名'),
                        content: TextFormField(
                          controller: _nameCtrl,
                          autofocus: true,
                        ),
                        actions: <Widget>[
                          TextButton(
                            child: Text('提交'),
                            onPressed: () {
                              Navigator.of(context).pop(_nameCtrl.value.text);
                              _nameCtrl.clear();
                            },
                          ),
                        ]);
                  },
                );
                Category _category = Category()..name = _name;
                await _category.store();
                setState(() {
                  categories.insert(0, _category);
                });
              },
              child: Text(
                '添加',
                style: TextStyle(fontSize: 16),
              ))
        ],
      ),
      body: SmartRefresher(
          controller: _refreshController,
          onRefresh: _getCategories,
          child: ListView.separated(
              separatorBuilder: listSeparatorBuilder,
              itemCount: categories.length > 0 ? categories.length : _loaded,
              itemBuilder: (BuildContext context, int index) {
                if (categories.isEmpty) return NoData();
                return Slidable(
                  key: ValueKey(index),
                  child: ListTile(
                    title: Text(categories[index].name),
                  ),
                  endActionPane: ActionPane(
                    motion: new DrawerMotion(),
                    children: <Widget>[
                      SlidableAction(
                        label: '删除',
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.red,
                        onPressed: (context) async {
                          final res = await showOkCancelAlertDialog(context: context, title: '确定删除?', message: '确定要删除该分类吗?');
                          if (res == OkCancelResult.ok) {
                            await categories[index].delete();
                            setState(() {
                              categories.removeAt(index);
                            });
                          }
                        },
                      ),
                    ],
                  ),
                );
              })),
    );
  }
}
